package com.gwsdk.paysdk.bean.pay;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.gwsdk.open.ApiCallback;
import com.gwsdk.open.FlagControl;
import com.gwsdk.paysdk.activity.GWWapPayActivity;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.bean.GWPayModel;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.entity.PayResult;
import com.gwsdk.paysdk.entity.WXOrderInfo;
import com.gwsdk.paysdk.entity.ZFBVerificationResult;
import com.gwsdk.paysdk.http.process.ZFBOrderInfoProcess;

public class ZfbPay {

	private final static String TAG = "ZfbPay";

	private boolean isBuyPtb;
	private boolean isWapPay;

	private Activity mActivity;
	private ZFBOrderInfoProcess zfbPay;
	private ZfbBuPtbEvent mZfbBuPtbEvent;

	public ZfbPay(Activity activity, boolean isWapPay){
		isBuyPtb = false;
		this.isWapPay = isWapPay;
		zfbPay = new ZFBOrderInfoProcess(this.isWapPay);
		if(null != activity){
			mActivity = activity;
		}
	}

	private final Handler zfbpayHandler = new Handler(Looper.getMainLooper()){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case Constant.ZFB_PAY_VALIDATE_SUCCESS:// 请求支付订单成功
					handlerZfbPayResult(msg.obj);
					break;
				case Constant.ZFB_PAY_VALIDATE_FAIL:// 请求支付订单失败
					FlagControl.flag = true;
					ToastUtil.show(mActivity, "支付失败：" + msg.obj.toString());
					break;
				case Constant.SDK_PAY_FLAG:// 支付结果
					handlerZfbSDKResult(msg.obj);
					break;
				case Constant.ZFB_WAPPAY_ORDERINFO_SUCCESS:
					WXOrderInfo zfbwapPayOrderInfo = (WXOrderInfo) msg.obj;
					Intent zfbWapPayintent = new Intent(mActivity, GWWapPayActivity.class);
					zfbWapPayintent.putExtra("WapPayOrderInfo", zfbwapPayOrderInfo);
					mActivity.startActivity(zfbWapPayintent);
					break;
				case Constant.ZFB_WAPPAY_ORDERINFO_FAIL:
					ToastUtil.show(mActivity, "支付失败：" + msg.obj);
					FlagControl.flag = true;
					break;
				default:
					break;
			}
		}
	};

	/**
	 * 支付宝app游戏充值
	 */
	public void zfbPayProcess(String coupon_id) {
		zfbPay.setGoodsName(ApiCallback.order().getProductName());
		zfbPay.setGoodsPrice(ApiCallback.order().getGoodsPriceYuan());
		zfbPay.setGoodsDesc(ApiCallback.order().getProductDesc());
		zfbPay.setServerName(ApiCallback.order().getServerName());
		zfbPay.setRoleName(ApiCallback.order().getRoleName());
		zfbPay.setRoleId(ApiCallback.order().getRoleId());
		zfbPay.setServerId(ApiCallback.order().getGameServerId());
		zfbPay.setExtra_param(ApiCallback.order().getExtra_param());
		zfbPay.setRoleLevel(ApiCallback.order().getRoleLevel());
		zfbPay.setGoodsReserve(ApiCallback.order().getGoodsReserve());
		zfbPay.setPayType("1");
		zfbPay.setCouponId(coupon_id);
		zfbPay.setExtend(ApiCallback.order().getExtendInfo());
		zfbPay.post(zfbpayHandler);
	}

	/**
	 * 支付宝wap游戏充值
	 */
	public void zfbPayWapProcess(Handler handler,String coupon_id) {
		zfbPay.setGoodsName(ApiCallback.order().getProductName());
		zfbPay.setGoodsPrice(ApiCallback.order().getGoodsPriceYuan());
		zfbPay.setGoodsDesc(ApiCallback.order().getProductDesc());
		zfbPay.setServerName(ApiCallback.order().getServerName());
		zfbPay.setRoleName(ApiCallback.order().getRoleName());
		zfbPay.setRoleId(ApiCallback.order().getRoleId());
		zfbPay.setServerId(ApiCallback.order().getGameServerId());
		zfbPay.setRoleLevel(ApiCallback.order().getRoleLevel());
		zfbPay.setGoodsReserve(ApiCallback.order().getGoodsReserve());
		zfbPay.setPayType("1");
		zfbPay.setCouponId(coupon_id);
		zfbPay.setExtend(ApiCallback.order().getExtendInfo());
		zfbPay.setExtra_param(ApiCallback.order().getExtra_param());
		zfbPay.post(handler);
	}

	/**
	 * 支付宝平台币充值
	 * @param goodsName 需要充值的物品名称
	 * @param goodsPrice 需要充值的物品价格
	 * @param goodsDesc
	 * @param zfbBuPtbEvent 支付回调接口
	 */
	public void zfbPayPTBProcess(String goodsName, String goodsPrice,
								 String goodsDesc, ZfbBuPtbEvent zfbBuPtbEvent){
		isBuyPtb = true;
		if(null != zfbBuPtbEvent){
			mZfbBuPtbEvent = zfbBuPtbEvent;
		}
		zfbPay.setGoodsName(goodsName);
		zfbPay.setGoodsPrice(goodsPrice);
		zfbPay.setGoodsDesc(goodsDesc);
		zfbPay.setPayType("0");
		zfbPay.setExtend("平台币充值");
		zfbPay.post(zfbpayHandler);
	}

	/**
	 * 支付宝平台币wap充值
	 * @param goodsName 需要充值的物品名称
	 * @param goodsPrice 需要充值的物品价格
	 * @param goodsDesc
	 * @param zfbBuPtbEvent 支付回调接口
	 */
	public void zfbPayPTBWapProcess(String goodsName, String goodsPrice,
								 String goodsDesc, ZfbBuPtbEvent zfbBuPtbEvent,Handler handler){
		isBuyPtb = true;
		if(null != zfbBuPtbEvent){
			mZfbBuPtbEvent = zfbBuPtbEvent;
		}
		zfbPay.setGoodsName(goodsName);
		zfbPay.setGoodsPrice(goodsPrice);
		zfbPay.setGoodsDesc(goodsDesc);
		zfbPay.setPayType("0");
		zfbPay.setExtend("平台币充值");
		zfbPay.post(handler);
	}

	/**
	 * 处理响应结果，支付宝发起支付
	 * @param obj
	 */
	private void handlerZfbPayResult(Object obj) {
//		Button btnPay=
		if(null == mActivity){
			GWLog.e(TAG, "支付页面已销毁");
			return;
		}
		ZFBVerificationResult zfbPayResult = (ZFBVerificationResult) obj;
		if (null == zfbPayResult) {
			GWLog.e(TAG, "支付宝支付参数为空");
			return;
		}
		if (TextUtils.isEmpty(zfbPayResult.getOrderInfo())) {
			String msg = zfbPayResult.getMsg();
			if (TextUtils.isEmpty(msg)) {
				msg = "验证订单失败,请重试";
			}
			GWLog.e(TAG , "error:" + msg);
			return;
		}
		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = zfbPayResult.getOrderInfo();

		new Thread(new Runnable() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(mActivity);
				FlagControl.flag = true;
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);
				Message msg = new Message();
				msg.what = Constant.SDK_PAY_FLAG;
				msg.obj = result;
				zfbpayHandler.sendMessage(msg);
			}
		}).start();
	}

	/**
	 * 9000支付成功  8000正在确认  4000订单支付失败
	 * 5000支付取消  6001支付取消  6002网络连接出错 6004未获取到支付结果
	 * 4001支付宝页面支付成功（目前sdk对4001的处理将其视为支付结果待确认状态，可以视为支付成功）
	 * 处理支付宝支付结果
	 */
	private void handlerZfbSDKResult(Object obj) {
		PayResult payResult = new PayResult((String) obj);
		String resultStatus = "-1";
		if (!TextUtils.isEmpty(payResult.getResultStatus())) {
			resultStatus = payResult.getResultStatus();
		}
		GWLog.e(TAG, "fun#handlerZfbSDKResult " + resultStatus);
		if (TextUtils.equals(resultStatus, "9000")) {
			resultStatus = "0";
		} else if (TextUtils.equals(resultStatus, "8000")||(TextUtils.equals(resultStatus,"4001"))) {
			resultStatus = "1";
		} else if (TextUtils.equals(resultStatus, "6004")) {
			resultStatus = "2";
		}

		if(isBuyPtb) {
			if(null != mZfbBuPtbEvent){
				boolean res = "0".equals(resultStatus) || "1".equals(resultStatus);
				mZfbBuPtbEvent.buyPTBResult(res);
			}
		}else {
			GWPayModel.Instance().getPck(resultStatus, "zfb").callback(resultStatus);
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					mActivity.finish();
				}
			}, 200);
		}
        FlagControl.flag=true;
	}
}
